package com.chushouya.product.service.admin.impl;

import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Check;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Lists;
import com.chushouya.product.dao.entity.ProductAttrEntity;
import com.chushouya.product.dao.repository.ProductAttrRepository;
import com.chushouya.product.dto.admin.product.AttrValueVO;
import com.chushouya.product.dto.admin.product.ProductAttrVO;
import com.chushouya.product.dto.admin.product.query.ProductAttrQuery;
import com.chushouya.product.service.admin.ProductAttrService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 商品属性业务实现
 */
@Service
public class ProductAttrServiceImpl implements ProductAttrService {

    @Resource
    private ProductAttrRepository productAttrRepository;


    @Override
    public void clearProductAttrByProductId(Long productId) {
        Check.notNull(productId, "商品ID不能为空");
        
        productAttrRepository.deleteByProductId(productId);
    }

    @Override
    public void batchInsertProductAttrEntities(List<ProductAttrEntity> productAttrList) {
        Check.notEmpty(productAttrList, "商品属性实体列表不能为空");
        
        Date now = new Date();
        
        // 设置创建时间
        productAttrList.forEach(entity -> {
            if (entity.getCreateTime() == null) {
                entity.setCreateTime(now);
            }
        });
        
        productAttrRepository.batchInsert(productAttrList);
    }

    @Override
    public List<ProductAttrVO> selectProductAttr(Long productId) {
        Check.notNull(productId, "商品ID不能为空");
        ProductAttrQuery query = new ProductAttrQuery();
        query.setProductId(productId);
        List<ProductAttrEntity> entityList = productAttrRepository.selectList(query);
        List<ProductAttrVO> dtoList = Lists.newArrayList();
        entityList.forEach(entity -> {
            ProductAttrVO dto = Beans.copy(entity,ProductAttrVO.class);
            List<AttrValueVO> attrValueList = Jsons.parseArray(entity.getAttrValues(), AttrValueVO.class);
            dto.setAttrValues(attrValueList);
            dtoList.add(dto);
        });
        return dtoList;


    }
}
